package com.lzy.webapi.controller;

import com.lzy.base.utils.PasswordUtil;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.exceptions.XBusinessException;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.MD5Utils;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.framework.tools.security.Digests;
import com.lzy.framework.tools.security.Encodes;
import com.lzy.product.apis.ProductUserServiceApi;
import com.lzy.product.dtos.ProductUserDto;
import com.lzy.webapi.request.AgentOrderRequest;
import com.lzy.webapi.request.LoginRequest;
import com.lzy.webapi.response.MemberBaseResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/login")
public class LoginController extends BaseController {
    private static final Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    ProductUserServiceApi productUserServiceApi;

    /**
     * 登录验证
     *
     * @throws
     */
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody
    Result login(LoginRequest request) {
        Ensure.that(request).isNotNull("00001005");
        Map<String, String> errMap = new HashMap();
        try {
            return new Result(onAuthenticationSuccess(request));
        } catch (XBusinessException e) {
            logger.error("登录失败----》" + e.getMessage());
            return new Result(e.getXCode(), e.getMessageWithoutCode(), null);
        } catch (Exception e) {
            logger.error("登陆出错---》" + e.getMessage());
            return new Result("-1", errMap.isEmpty() ? "验证失败" : errMap.get("errMsg"), null);
        }
    }

    private MemberBaseResponse onAuthenticationSuccess(LoginRequest request) {
        Ensure.that(request).isNotNull("00001005");
        //登录验证账号密码
        ProductUserDto userDto = new ProductUserDto();
        Ensure.that(request.getLoginName()).isNotEmpty("01000003");
        userDto.setLoginName(request.getLoginName());
        Ensure.that(request.getPassword()).isNotEmpty("01000002");
        ProductUserDto dto = productUserServiceApi.findUserByCont(userDto);
        Ensure.that(dto).isNotNull("01000001");
        byte[] salt = Encodes.decodeHex(dto.getSalt());
        byte[] hashPassword = Digests.md5(request.getPassword().getBytes(), salt,
                Integer.valueOf(PasswordUtil.hashIntegrations));
        userDto.setPassword(Encodes.encodeHex(hashPassword));
        dto = productUserServiceApi.findUserByCont(userDto);
        Ensure.that(dto).isNotNull("01000004");
        //3.调用父类方法，返回对象
        MemberBaseResponse response = super.getMemberBaseResponseByParam(dto, null);
        return response;
    }

    /**
     * 错误转向
     *
     * @throws
     */
    @RequestMapping(value = "/errors/{code}")
    public String login(@PathVariable("code") String code) {
        if (StringUtil.isNotEmpty(code))
            return "errors/" + code;
        return "error/404";
    }


}

